using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Colorprj.Common;
namespace Colorprj
{
    public partial class frmSalesReturn : Form
    {
        ProductMasterData pmd = new ProductMasterData();
        Colorprj.Masters.SubProductManager spm = new Colorprj.Masters.SubProductManager();
        SalesReturn.SalesReturnManager cm = new Colorprj.SalesReturn.SalesReturnManager();
        Colorprj.Masters.BuyerManager bm = new Colorprj.Masters.BuyerManager(); 

        public frmSalesReturn()
        {
            InitializeComponent();
        }

        private void frmSalesReturn_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'colorPrjBuyer.Buyer' table. You can move, or remove it, as needed.
            //this.buyerTableAdapter.Fill(this.colorPrjBuyer.Buyer);
            cboParty.DataSource = bm.GetAllBuyers().Tables[0];
            cboParty.DisplayMember = "BuyerName";
            cboParty.ValueMember = "BuyerId";

            SubProduct.DataSource = spm.GetAllProducts().Tables[0];

            SubProduct.DisplayMember = "subProductName";
            SubProduct.ValueMember = "subProductId"; 
        }

        private void dataGridView2_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            //if (this.dataGridView2.CurrentCell.ColumnIndex == SubProduct.Index)
            //{
            //    DataGridViewComboBoxEditingControl control = e.Control as DataGridViewComboBoxEditingControl;
            //    BindingSource bs = control.DataSource as BindingSource;
            //    if (bs != null)
            //    {
            //        // set the filteredChildBS as the DataSource of the editing control
            //        (e.Control as ComboBox).DataSource = filteredChildBS;

            //        object regionvalue = this.dataGridView2.Rows[this.dataGridView2.CurrentCell.RowIndex].Cells[Product.Index].Value;
            //        if (regionvalue == DBNull.Value || regionvalue == null)
            //        {
            //            filteredChildBS.Filter = "Productid=-1";
            //        }
            //        else
            //        {
            //            filteredChildBS.Filter = "Productid=" + regionvalue.ToString();
            //        }
            //        // set the SelectedValue property of the editing control
            //        if (this.dataGridView2.CurrentCell.Value != DBNull.Value && this.dataGridView2.CurrentCell.Value != null)
            //        {
            //            control.SelectedValue = this.dataGridView2.CurrentCell.Value;
            //        }
            //    }
            //}

        }

        private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {

            if (e.RowIndex >= 0 && e.ColumnIndex == 0)
            {

                int myval = Convert.ToInt16(this.dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
                this.dataGridView2.Rows[e.RowIndex].Cells["Rate"].Value = cm.GetSubProductById(myval).SaleRate;
                this.dataGridView2.Rows[e.RowIndex].Cells["Stock"].Value = cm.GetSubProductById(myval).Stock;

            }


        }
        private void dataGridView2_RowLeave(object sender, DataGridViewCellEventArgs e)
        {


            if (dataGridView2[0, e.RowIndex].Value != null
                && dataGridView2[1, e.RowIndex].Value != null
                && Convert.ToInt16(dataGridView2[2, e.RowIndex].Value) != 0
                && Convert.ToDecimal(dataGridView2[3, e.RowIndex].Value) != 0)
            {

                // string aa = dataGridView2[1, e.RowIndex].Value.ToString() ;
                dataGridView2.AllowUserToAddRows = true;

            }
            else
            {
                if (dataGridView2.RowCount > 1) dataGridView2.AllowUserToAddRows = false;


            }
        }

        private void dataGridView2_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView2["Amount", e.RowIndex].Value = Convert.ToDecimal(dataGridView2["Qty", e.RowIndex].Value) * Convert.ToDecimal(dataGridView2["Rate", e.RowIndex].Value);

            if (dataGridView2.Rows.Count > 0)
            {
                txtTotal.Text = Total().ToString("F2");
                txtSRAmount.Text = Convert.ToString(Utility.getDecimalVal(txtTotal.Text) + Utility.getDecimalVal(txtTaxAmount.Text));  
            }

        }
        private double Total()
        {
            double tot = 0;
            int i = 0;
            for (i = 0; i < dataGridView2.Rows.Count; i++)
            {
                tot = tot + Convert.ToDouble(dataGridView2.Rows[i].Cells["Amount"].Value);
            }
            return tot;
        }
        private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView2.Rows[e.RowIndex].ErrorText = String.Empty;

        }
        private void dataGridView2_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            string headerText = dataGridView2.Columns[e.ColumnIndex].HeaderText;


            if (headerText.Equals("Sub-prd"))
            {
                if (string.IsNullOrEmpty(e.FormattedValue.ToString()))
                {
                    dataGridView2.Rows[e.RowIndex].ErrorText =
                        "Sub Product must not be empty";
                    e.Cancel = true;
                }

                if (IsDuplicate(e.FormattedValue.ToString()) && dataGridView2.Rows[e.RowIndex].Cells["SalesReturnDetId"].Value == null)
                {
                    dataGridView2.Rows[e.RowIndex].ErrorText =
                                "Sub Product Allready Exist";
                    e.Cancel = true;

                }

            }
            if (headerText.Equals("Qty"))
            {
                double curQty = Utility.getDblVal(e.FormattedValue.ToString());
                double OldQty = Utility.getDblVal(dataGridView2.Rows[e.RowIndex].Cells["OldQty"].Value);
                double StockQty = Utility.getDblVal(dataGridView2.Rows[e.RowIndex].Cells["Stock"].Value);
                if (curQty > OldQty + StockQty)
                {

                    dataGridView2.Rows[e.RowIndex].ErrorText =
                                    "Qty is greater then avialable qty in stock";
                    e.Cancel = true;
                }
            }
        }
        private bool IsDuplicate(string spvalue)
        {
            bool retval = false;
            int rowCnt = 0;
            System.Collections.Hashtable hash = new System.Collections.Hashtable();

            for (rowCnt = 0; rowCnt < dataGridView2.RowCount - 1; rowCnt++)
            {
                String SubproductId = dataGridView2["Subproduct", rowCnt].FormattedValue.ToString();
                if (hash.Contains(spvalue))
                {
                    retval = true;
                    break;
                }
                else
                {
                    hash.Add(SubproductId, SubproductId);
                }

            }
            return retval;
        }

        private SalesReturn.SalesReturnHeadEntity getFormData()
        {
            SalesReturn.SalesReturnHeadEntity phEntity = new Colorprj.SalesReturn.SalesReturnHeadEntity();
            phEntity.BuyerId = Convert.ToInt16(cboParty.SelectedValue);
            phEntity.SalesReturnNo = txtSalesReturnNo.Text;
            phEntity.SalesReturnDate = dtSalesReturnDate.Value;


            phEntity.TotalAmount = Utility.getDblVal(txtTotal.Text);
            phEntity.TaxAmount = Utility.getDblVal(txtTaxAmount.Text);
            phEntity.SRAmount = Utility.getDblVal(txtSRAmount.Text);

            if (!txtSalesReturnHeadId.Text.Trim().Equals(""))
            {
                phEntity.SalesReturnHeadId = Convert.ToInt16(txtSalesReturnHeadId.Text);
            }

            List<SalesReturn.SalesReturnDetailEntity> pdEntityList = new List<Colorprj.SalesReturn.SalesReturnDetailEntity>();
            int rowCnt = 0;
            for (rowCnt = 0; rowCnt < dataGridView2.RowCount; rowCnt++)
            {
                //int prdId = Convert.ToInt16(dataGridView2["Product", rowCnt].Value);
                //int subPrdId = Convert.ToInt16(dataGridView2["Subproduct", rowCnt].Value);
                //int qty = Convert.ToInt16(dataGridView2["Qty", rowCnt].Value);
                //if (qty > 0)
                //{
                SalesReturn.SalesReturnDetailEntity pdEntity = new Colorprj.SalesReturn.SalesReturnDetailEntity();
                //pdEntity.ProductId = Convert.ToInt16(dataGridView2["Product", rowCnt].Value);
                pdEntity.Qty = Convert.ToDouble(dataGridView2["Qty", rowCnt].Value);
                pdEntity.OldQty = Convert.ToDouble(dataGridView2["OldQty", rowCnt].Value);
                pdEntity.Rate = Convert.ToDouble(dataGridView2["Rate", rowCnt].Value);
                pdEntity.Amount = Convert.ToDouble(dataGridView2["Amount", rowCnt].Value);
                pdEntity.SubproductId = Convert.ToInt16(dataGridView2["Subproduct", rowCnt].Value);
                pdEntity.SalesReturnDetailId = Convert.ToInt16(dataGridView2["SalesReturnDetId", rowCnt].Value);
                if (pdEntity.Qty > 0 || pdEntity.SalesReturnDetailId > 0)
                {
                    pdEntityList.Add(pdEntity);
                }
                //}
            }
            phEntity.SalesReturnDetailList = pdEntityList;
            return phEntity;
        }


        private void btnSave_Click(object sender, EventArgs e)
        {

            try
            {
                SalesReturn.SalesReturnHeadEntity phEntity = getFormData();
                SalesReturn.SalesReturnManager cm = new SalesReturn.SalesReturnManager();
                cm.AddSalesReturn(phEntity);
            } catch (Exception ex){

                MessageBox.Show(ex.Message); 
            
            }
            DialogResult result = MessageBox.Show("SalesReturn Saved ! do you wanr to pritn", "", MessageBoxButtons.YesNo);

            if (result == System.Windows.Forms.DialogResult.Yes)
            {
                //frmrptSalesReturn frmchPrint = new frmrptSalesReturn();
                //frmchPrint.SalesReturnNo = cm.GetLastSalesReturnNo();
                //frmchPrint.ShowDialog();

            }


            ClearForm(this.Controls);
        }
        //private void ClearForm()
        //{

        //    btnSave.Enabled = true;
        //    btnUpdate.Enabled = false;
        //    //this.dataGridView2.Rows.Clear();
        //    txtSalesReturnHeadId.Text = "";
        //    txtTotal.Text = "";
        //    //txtPurNo.Text = "";
        //    // cboParty.SelectedIndex = -1;
        //    //foreach (Control c in Form.ControlCollection )
        //    //{
        //    //    if (c is TextBox)
        //    //    {
        //    //        ((TextBox)c).Text = ((TextBox)c).Text + ((TextBox)c).Name + "\n";
        //    //    }
        //    //}
        //    Control.ControlCollection coll = this.Controls;
        //    //List<ComboBox> list33 = GetControlsOfType<ComboBox>(coll);
        //    foreach (Control c in coll)
        //    {
        //        //if (c != null)
        //        //    Console.WriteLine(c.Text, "Index numb: " + coll.GetChildIndex(c, false));
        //        if (c is TextBox) c.Text = string.Empty;
        //        if (c is DataGridView) { ((DataGridView)c).Rows.Clear(); }
        //        if (c is ComboBox)
        //        {
        //            ((ComboBox)c).SelectedIndex = -1;
        //        }
        //    }





        //}

        public void ClearForm(Control.ControlCollection coll)
        {
            // Control.ControlCollection coll = this.Controls;
            foreach (Control c in coll)
            {
                if (c.HasChildren) ClearForm(c.Controls);
                if (c is TextBox) c.Text = string.Empty;
                if (c is DataGridView) { ((DataGridView)c).Rows.Clear(); }
                if (c is ComboBox)
                {
                    ((ComboBox)c).SelectedIndex = -1;
                }
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            //frmSalesReturnSearch ps = new frmSalesReturnSearch();
            //SalesReturn.SalesReturnManager cm = new Colorprj.SalesReturn.SalesReturnManager();
            //if (ps.ShowDialog() == DialogResult.OK)
            //{

            //    int SalesReturnId = Convert.ToInt16(ps.ItemToRead);


            //    SalesReturn.SalesReturnHeadEntity phEntity = cm.GetSalesReturn(SalesReturnId);
            //    txtSalesReturnHeadId.Text = SalesReturnId.ToString();
            //    txtSalesReturnNo.Text = phEntity.SalesReturnNo;
            //    dtSalesReturnDate.Value = phEntity.SalesReturnDate;
            //    cboParty.SelectedValue = phEntity.BuyerId;
            //    txtTotal.Text = phEntity.TotalAmount.ToString();

            //    if (phEntity.InvoiceId > 0 || phEntity.Printed)
            //    {

            //        dataGridView2.Enabled = false;
            //        btnUpdate.Enabled = false;
            //    }
            //    else
            //    {

            //        btnUpdate.Enabled = true;
            //        dataGridView2.Enabled = true;
            //    }
            //    btnSave.Enabled = false;
            //    dataGridView2.RowCount = phEntity.SalesReturnDetailList.Count + 1;
            //    int row = 0;
            //    foreach (SalesReturn.SalesReturnDetailEntity pdEntity in phEntity.SalesReturnDetailList)
            //    {

            //        //dataGridView2["Product", row].Value = pdEntity.ProductId;
            //        dataGridView2["SubProduct", row].Value = pdEntity.SubproductId;
            //        dataGridView2["Qty", row].Value = pdEntity.Qty;
            //        dataGridView2["Rate", row].Value = pdEntity.Rate;
            //        dataGridView2["Amount", row].Value = pdEntity.Amount;
            //        dataGridView2["SalesReturnDetId", row].Value = pdEntity.SalesReturnDetailId;
            //        dataGridView2["OldQty", row].Value = pdEntity.Qty;
            //        row++;

            //    }


            //}
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            SalesReturn.SalesReturnHeadEntity phEntity = getFormData();
            SalesReturn.SalesReturnManager pm = new Colorprj.SalesReturn.SalesReturnManager();
            pm.UpdSalesReturn(phEntity);
            ClearForm(this.Controls);
        }

        private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {

        }

        private void dataGridView2_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView2["Amount", e.RowIndex].Value = Convert.ToDecimal(dataGridView2["Qty", e.RowIndex].Value) * Convert.ToDecimal(dataGridView2["Rate", e.RowIndex].Value);
            txtSRAmount.Text = Convert.ToString(Utility.getDecimalVal(txtTotal.Text) + Utility.getDecimalVal(txtTaxAmount.Text));  
            dataGridView2.AllowUserToAddRows = true;
        }

        private void dataGridView2_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (Utility.getDblVal(dataGridView2.Rows[e.RowIndex].Cells["Qty"].Value) <= 0 && dataGridView2.Rows[e.RowIndex].Cells["SalesReturnDetId"].Value == null)
            {
                dataGridView2.Rows[e.RowIndex].ErrorText =
                       "Qty must not be 0";
                e.Cancel = true;
            }
        }

        private void txtTaxAmount_TextChanged(object sender, EventArgs e)
        {
            txtSRAmount.Text = Convert.ToString(Utility.getDecimalVal(txtTotal.Text) + Utility.getDecimalVal(txtTaxAmount.Text));  
        }

        private void dataGridView2_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
        {

        }

        //private void btnCancel_Click_1(object sender, EventArgs e)
        //{

        //}

        //private void btnEdit_Click_1(object sender, EventArgs e)
        //{

        //}

        //private void btnSave_Click_1(object sender, EventArgs e)
        //{

        //}

        //private void btnUpdate_Click_1(object sender, EventArgs e)
        //{

        //}

        //private void btnCancel_Click_1(object sender, EventArgs e)
        //{

        //}

        //private void btnEdit_Click_1(object sender, EventArgs e)
        //{

        //}

        //private void btnSave_Click_1(object sender, EventArgs e)
        //{

        //}
    }
}